//
//  MHTopicMainViewController.m
//  ManHua
//
//  Created by 赵永泉 on 15/10/24.
//  Copyright © 2015年 蓝欧科技. All rights reserved.
//

#import "MHTopicMainViewController.h"

#import "MHTopicListRecommendTableViewCell.h"
#import "MHInformationTableViewCell.h"
#import "MHComicDetailViewController.h"
#import "MHTopicMoreBookListCollectionViewController.h"
#import "MHMainTopicModel.h"
#import "MHComicIntroduct.h"
#import "MHTopicBannerModel.h"
#import "MHTopicMoreBookShowCollectionViewController.h"
#import <AFNetworking.h>
#import "MHTopicHeadrView.h"
#import "MJRefresh.h"
#import "MHDataManager.h"
@interface MHTopicMainViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *topicArr;
@property(nonatomic,strong) MHInformationTableViewCell *informationCell;
@property(nonatomic,strong) MHTopicListRecommendTableViewCell *recommendCell;
@property(nonatomic,strong)NSMutableArray *RecommedbookArr;//所有图书的数组
@property(nonatomic,strong)NSMutableArray *cellBookArr;//这些漫画推荐的数组
@property(nonatomic,strong)NSString *topicID;//Book请求数据id
@property(nonatomic,strong)NSMutableArray *BookIDModelArr;//类型是Book的专题
@property(nonatomic,strong)NSMutableArray *implatArr;//漫画期刊里面的数组
@property(nonatomic,strong)NSString *ID;//专题请求数据的id
@property(nonatomic,strong)NSMutableArray *TopicModelArr;
@property(nonatomic,strong)NSMutableArray *allTopicArr;
@property(nonatomic,strong)NSMutableArray *InformationArr;
@property(nonatomic,strong)NSMutableArray *boyArr;
@property(nonatomic,strong)NSMutableArray *girlArr;
@property(nonatomic,strong)NSMutableArray *favoriteArr;
@property(nonatomic,strong)NSMutableArray *bannerArr;
@property(nonatomic,strong)FMDatabase *dataBase;//数据库
@end

@implementation MHTopicMainViewController
-(NSMutableArray *)bannerArr
{
    if (_bannerArr==nil) {
        _bannerArr=[NSMutableArray arrayWithCapacity:0];
        
    }
    return _bannerArr;
}
-(NSMutableArray *)InformationArr
{if(_InformationArr==nil)
{
    _InformationArr=[NSMutableArray arrayWithCapacity:0];
}
    return _InformationArr;
    
}
-(NSMutableArray *)boyArr
{if(_boyArr==nil)
{
    _boyArr=[NSMutableArray arrayWithCapacity:0];
}
    return _boyArr;
}
-(NSMutableArray *)girlArr
{
    if (_girlArr==nil) {
        _girlArr=[NSMutableArray arrayWithCapacity:0];
    }
    return _girlArr;
}
-(NSMutableArray *)favoriteArr
{
    if (_favoriteArr==nil) {
        _favoriteArr=[NSMutableArray arrayWithCapacity:0];
    }
    return _favoriteArr;
}
-(NSMutableArray *)allTopicArr
{
    
    if (_allTopicArr==nil) {
        _allTopicArr=[NSMutableArray arrayWithCapacity:0];
        
    }
    return _allTopicArr;
}
-(NSMutableArray *)TopicModelArr
{
    if (_TopicModelArr==nil) {
        _TopicModelArr=[NSMutableArray arrayWithCapacity:0];
    }
    return _TopicModelArr;
}
-(NSMutableArray *)implatArr
{
    if (_implatArr==nil) {
        _implatArr=[NSMutableArray arrayWithCapacity:0];
    }
    return _implatArr;
}
-(NSMutableArray *)cellBookArr
{
    if (_cellBookArr==nil) {
        _cellBookArr=[NSMutableArray arrayWithCapacity:0];
    }
    return _cellBookArr;
}
-(NSMutableArray *)BookIDModelArr
{
    if (_BookIDModelArr==nil) {
        self.BookIDModelArr=[NSMutableArray arrayWithCapacity:0];
    }
    return _BookIDModelArr;
}
-(NSMutableArray *)topicArr
{
    if (_topicArr==nil) {
        self.topicArr=[NSMutableArray array];
    }
    return _topicArr;
}
-(NSMutableArray *)RecommedbookArr
{
    if (_RecommedbookArr==nil) {
        _RecommedbookArr=[NSMutableArray arrayWithCapacity:0];
    }
    return _RecommedbookArr;
}

#pragma -请求主页面的主题数据
-(void)mainPageTopicData
{
    NSMutableDictionary *dict=[NSMutableDictionary dictionary];
    dict[@"method"]=@"RecommandTopic";
    
    [[AFHTTPRequestOperationManager manager]GET:@"http://112.124.96.190:9090/bukamanhua5appjobs/ComicHandle.ashx" parameters:dict success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        //每次进行网络请求的时候把数据库以前都数据删除掉
        
        [[MHDataManager shareManager]deleteValueFromeTable:@"TOPICMANMODEL"];
        [self.topicArr removeAllObjects];
        NSArray *dataArray=responseObject;
        [dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            MHMainTopicModel *mainTopicModel=[[MHMainTopicModel alloc]init];
            [mainTopicModel setValuesForKeysWithDictionary:obj];
            [self.topicArr addObject:mainTopicModel];
            
            
            [[MHDataManager shareManager]insertValueToTabel:@"TOPICMANMODEL" mainTopicModel:mainTopicModel];
            
        }];
        
        [self.tableView reloadData];
        [self acquireTopicAllBookData];
        [self acquireAllTopicData];
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"主页面的主题数据请求失败");
    }];
    
    
}
#pragma mark -请求collection中的数据
-(void)achieveAllBookVisibleIDs
{
    [self.BookIDModelArr removeAllObjects];
    self.topicID=@"";
    [self.topicArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        MHMainTopicModel *TopicModel=(MHMainTopicModel *)obj;
        if ([TopicModel.Type isEqualToString:@"Book"]) {
            self.topicID=  [[self.topicID stringByAppendingString:TopicModel.VisibleIDs] stringByAppendingString:@"#" ];
            [self.BookIDModelArr addObject:TopicModel];
            NSLog(@"%@",TopicModel.Type);
        }
    }];
    
    
}
-(void)acquireTopicAllBookData
{
    [self achieveAllBookVisibleIDs];
    NSMutableDictionary *ParDict=[NSMutableDictionary dictionary];
    ParDict[@"method"]=@"search";
    ParDict[@"name"]=self.topicID;
    ParDict[@"type"]=@"2";
    [self.RecommedbookArr removeAllObjects];
    [[AFHTTPRequestOperationManager manager]GET:@"http://112.124.96.190:9090/bukamanhua5appjobs/ComicHandle.ashx" parameters:ParDict success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        
        [[MHDataManager shareManager]deleteValueFromeTable:@"MHComicIntroduct"];
        NSArray *allBookArr=responseObject;
        
        [allBookArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            MHComicIntroduct *mainBookModel=[[MHComicIntroduct alloc]init];
            [mainBookModel setValuesForKeysWithDictionary:obj];
            [self.RecommedbookArr addObject:mainBookModel];
            [[MHDataManager shareManager]insertValueToTabel:@"MHComicIntroduct" ComicIntroduce:mainBookModel];
            
        }];
        
        
        [self topicDataSection];
        
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"Book请求数据失败");
        
    }];
}
#pragma mark -请求轮播图中topic的数据的数据
-(void)achieveAllTopicOfVisableIDs
{
    
    [self.TopicModelArr removeAllObjects];
    self.ID=@"";
    [self.topicArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        MHMainTopicModel *TopicModel=(MHMainTopicModel *)obj;
        if ([TopicModel.Type isEqualToString:@"Topic"]) {
            self.ID=  [[self.ID stringByAppendingString:TopicModel.VisibleIDs] stringByAppendingString:@"#" ];
            [self.TopicModelArr addObject:TopicModel];
            NSLog(@"这里有数据吗？%@",TopicModel.Type);
        }
    }];
    
}
-(void)acquireAllTopicData
{
    [self achieveAllTopicOfVisableIDs];
    NSMutableDictionary *Dict=[NSMutableDictionary dictionary];
    Dict[@"method"]=@"GetTopicLikeByTopicID";
    Dict[@"TopicID"]=self.ID;
    [self.allTopicArr removeAllObjects];
    dispatch_async(dispatch_get_main_queue(), ^{
        [[AFHTTPRequestOperationManager manager] GET:@"http://112.124.96.190:9090/bukamanhua5appjobs/ComicHandle.ashx" parameters:Dict success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
            
            [[MHDataManager shareManager]deleteValueFromeTable:@"TOPICBANNER"];
            [responseObject enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                MHTopicBannerModel *bannerModel=[[MHTopicBannerModel alloc]init];
                [bannerModel setValuesForKeysWithDictionary:obj];
                
                [[MHDataManager shareManager]insertValueToTabel:@"TOPICBANNER" bannerModel:bannerModel];
                [self.allTopicArr addObject:bannerModel];
            }];
            //获取分区的数据
            [self sectionTopicData];
            //加载tableView的头视图
            [self loadingTableViewHeader];
            
            [self.tableView.header endRefreshing];
        } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
            NSLog(@"%@", error.localizedDescription);
            
        }];
        
    });
    
    
}
//分区的专题数据


-(void)loadingTableViewHeader
{
    __weak MHTopicMainViewController *test=self;
    MHTopicHeadrView *topicHeaderView=[[MHTopicHeadrView alloc]initWithFrame:CGRectMake(0, 0, Width, 640.0 / 1024.0 * Width)];
    topicHeaderView.carouseDatasourceArr=self.bannerArr;
    self.tableView.tableHeaderView = topicHeaderView;
    topicHeaderView.tapToBookCVCBlock=^(MHTopicBannerModel *bannerModel)
    {
        
        MHTopicMoreBookListCollectionViewController *moreBookListCVC=[[MHTopicMoreBookListCollectionViewController alloc]init];
        moreBookListCVC.title=bannerModel.TopicName;
        if ([bannerModel.TopicType isEqualToString:@"Book"]) {
            moreBookListCVC.bannerModel=bannerModel;
            [test.navigationController pushViewController:moreBookListCVC animated:YES];
        }
        else
        {
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:bannerModel.TopicDescription]];
        }
        
    };
    
}
-(void)sectionTopicData
{
    [self.InformationArr removeAllObjects];
    [self.boyArr removeAllObjects];
    [self.girlArr   removeAllObjects];
    [self.favoriteArr   removeAllObjects];
    [self.bannerArr removeAllObjects];
    [self .TopicModelArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        MHMainTopicModel *maintopModel=(  MHMainTopicModel*)obj;
        
        for (MHTopicBannerModel *model in self.allTopicArr) {
            NSString *TopicID=[NSString stringWithFormat:@"%ld",model.TopicID];
            if (idx==0&&[maintopModel.VisibleIDs rangeOfString:TopicID].length>0) {
                [self.bannerArr addObject:model];
                
                
            }
            else if (idx==1&&[maintopModel.VisibleIDs rangeOfString:TopicID].length>0)
            {
                [self.InformationArr addObject:model];
            }
            else if (idx==2&&[maintopModel.VisibleIDs rangeOfString:TopicID].length>0)
            {
                [self.girlArr addObject:model];
            }
            else if(idx==3 &&[maintopModel.VisibleIDs rangeOfString:TopicID].length>0)
            {
                [self.boyArr addObject:model];
            }
            else if (idx==4&&[maintopModel.VisibleIDs rangeOfString:TopicID].length>0)
            {
                [self.favoriteArr   addObject:model];
                [self.tableView reloadData];
            }
            
        }
    }];
}
//分区漫画书数据
-(void)topicDataSection;

{
    [self.cellBookArr   removeAllObjects];
    [self.implatArr removeAllObjects];
    [self.BookIDModelArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        MHMainTopicModel *maintopModel=(  MHMainTopicModel*)obj;
        NSLog(@"%@",maintopModel.VisibleIDs);
        for ( MHComicIntroduct *model in  self.RecommedbookArr) {
            NSString *bookID = [NSString stringWithFormat:@"%ld", (long)model.BookID] ;
            if (idx==0&&[maintopModel.VisibleIDs rangeOfString:bookID].length > 0 ) {
                [self.cellBookArr addObject:model];
                NSLog(@"%d",self.cellBookArr.count);
            }
            else if (idx==1&&[maintopModel.VisibleIDs rangeOfString:bookID].length>0)
            {
                [self.implatArr  addObject:model];
                NSLog(@"这里有值不？？？？why,why,%d",self.implatArr.count);
                [self.tableView reloadData];
                [self.recommendCell.collectionView reloadData];
                
            }
        }
    }];
    
}

#pragma mark -数据持久化打开数据库
-(void)openDataBase
{
    [[MHDataManager shareManager]createTable];
    
    
}
#pragma mark -根据查找语句查找表里面的内容
-(void)findDataBaseValue
{
    self.topicArr = [[MHDataManager shareManager]findMainTopicModelData:@"TOPICMANMODEL"];
    self.allTopicArr=[[MHDataManager shareManager]findMainTopicModelData:@"TOPICBANNER"];
    self.RecommedbookArr=[[MHDataManager shareManager]findMainTopicModelData:@"MHComicIntroduct"];
    NSLog(@"%ld,%ld,%ld",self.topicArr.count,self.allTopicArr.count,self.RecommedbookArr.count);
    
}
-(void)locationDataView
{
    if (self.RecommedbookArr.count!=0&&self.allTopicArr.count!=0&&self.topicArr.count!=0) {
        
        
        [self achieveAllBookVisibleIDs];
        [self topicDataSection  ];
        [self achieveAllTopicOfVisableIDs  ];
        
        
        [self sectionTopicData];
        
        [self loadingTableViewHeader];
        NSLog(@"%@", self.tableView);
        [self.tableView reloadData];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.title = @"专题";
    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:kThemeColor,UITextAttributeTextColor,nil];
#warning 进入页面首先先进请求本地数据
#pragma -mark 打开数据库
    [self openDataBase];
#pragma -mark 请求本地数据
    [self findDataBaseValue];
#pragma -mark 加载tableView页面
    [self mainTopicListPage];
#pragma -mark  对本地的数据进行处理,然后加载头视图
    [self locationDataView];
    
    
    [self mainPageTopicData];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
#pragma 进行数据的刷新
    self.tableView.header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self mainPageTopicData];
    }];
    //    [self.tableView.header beginRefreshing];
}

#pragma mark -专题主页面list
-(void)mainTopicListPage
{
    
    self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0,Width, Height)];
    [self.tableView registerClass:[MHTopicListRecommendTableViewCell class] forCellReuseIdentifier:@"MHTopicListRecommendTableViewCell"];
    [self.tableView registerClass:[MHInformationTableViewCell class] forCellReuseIdentifier:@"MHInformationTableViewCell"];
    self.tableView.rowHeight=400;
    self.tableView.dataSource=self;
    self.tableView.delegate=self;
    [self.view addSubview:self.tableView];
    
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.topicArr.count-1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    __weak MHTopicMainViewController *test=self;
    if (indexPath.row ==0||indexPath.row==self.topicArr.count-3) {
        
        self.recommendCell=[tableView  dequeueReusableCellWithIdentifier:@"MHTopicListRecommendTableViewCell" forIndexPath:indexPath];
        self.recommendCell.mainTopicModel=self.topicArr[indexPath.row+1];
        
        if (indexPath.row==0) {
            self.recommendCell.bookArr=self.cellBookArr;
        }
        else
        {
            self.recommendCell.bookArr=self.implatArr;
        }
        
        
        self.recommendCell.bookPageBlock=^(MHMainTopicModel *mainTopicModel)
        {
            
            MHTopicMoreBookListCollectionViewController *topicMoreBoolListCVC=[[MHTopicMoreBookListCollectionViewController alloc]init];
            topicMoreBoolListCVC.title=mainTopicModel.Title;
            topicMoreBoolListCVC.mainTopicModel=mainTopicModel;
            [test.navigationController pushViewController:topicMoreBoolListCVC animated:YES];
        };
        
        self.recommendCell.comicDetailVCBlock=^(MHComicIntroduct *comicIntroduct){
            MHComicDetailViewController *comicDetailVC=[[MHComicDetailViewController alloc]init];
            comicDetailVC.comicIntroduct = comicIntroduct;
            [test.navigationController pushViewController:comicDetailVC animated:YES];
            
        };
        return self.recommendCell;
        
    }
    else if(self.topicArr.count != 0)
    {
        self.informationCell=[tableView dequeueReusableCellWithIdentifier:@"MHInformationTableViewCell" forIndexPath:indexPath];
        self.informationCell.topicTopicModel=self.topicArr[indexPath.row+1];
        
        if (indexPath.row==1) {
            self.informationCell.dataSourceArr=self.InformationArr;
        }
        else if (indexPath.row==2)
        {
            self.informationCell.dataSourceArr=self.girlArr;
        }
        else if (indexPath.row==3)
        {
            self.informationCell.dataSourceArr=self.boyArr;
        }
        else if (indexPath.row==5)
        {
            self.informationCell.dataSourceArr=self.favoriteArr;
        }
        
        self.informationCell.moreBookCVCBlock=^(MHTopicBannerModel *bannerModel,NSString*titleName)
        {
            
            MHTopicMoreBookListCollectionViewController *topicMoreBoolListCVC=[[MHTopicMoreBookListCollectionViewController alloc]init];
            topicMoreBoolListCVC.bannerModel=bannerModel;
            topicMoreBoolListCVC.title=bannerModel.TopicName;
            [test.navigationController pushViewController:topicMoreBoolListCVC animated:YES];
        };
        
        self.informationCell.showCVCBlock=^(MHMainTopicModel *topicModel)
        {
            
            MHTopicMoreBookShowCollectionViewController *showCVC=[[MHTopicMoreBookShowCollectionViewController    alloc]init];
            showCVC.mainTopicModel=topicModel;
            showCVC.title=topicModel.Title;
            [test.navigationController pushViewController:showCVC animated:YES];
        };
        return  self.informationCell;
        
        
        
    }
    return [[UITableViewCell alloc]init];
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if(indexPath.row==0||indexPath.row==self.topicArr.count-3)
    {
        
        MHTopicListRecommendTableViewCell *cell=[[MHTopicListRecommendTableViewCell   alloc]init];
        CGFloat hight=[cell heighOfCell];
        return  hight ;
        
    }
    else
    {
        MHInformationTableViewCell *cell=[[MHInformationTableViewCell alloc]init];
        return cell.heightCell;
    }
}


@end
